require 'set'

module ActionView
  module Helpers
    
    # Provides helpers that generate jQuery UI code.
    #
    module JQueryUIHelper
      
      @@dlg_seq = 0
      @@box_seq = 0
      
      # Returns a link which request a remote action and use jQuery UI dialog
      # to display the response.
      #
      # Specify the dialog's id by <tt>dialog[:id]</tt>
      #
      # @author ericsk
      # @since 0.2
      def jquery_link_to_remote_dialog(name, options = {}, dialog = {}, html = {})
        unless dialog[:id] and dialog[:id].length > 0
          dialog[:id] = "my_dlg#{@@dlg_seq}"
          @@dlg_seq = @@dlg_seq + 1
        end
        # add the dialog container.
        dialog[:theme] ||= "flora"
        c = content_tag("div", "", html.merge({
          :id => "#{dialog[:id]}",
          :style => "display:none;",
          :class => dialog[:theme]
        }))
        # store the response in the dialog container.
        options[:update] = dialog[:id]
        options[:complete] = "$('##{dialog[:id]}').dialog();"+
          "$('##{dialog[:id]}').show();"
        c.concat(content_tag("a", name, html.merge({
          :href => html[:href] || "#",
          :onclick => "#{jq_remote_func(options)}; return false; "          
        })))
      end
      alias_method :jq_link_to_remote_dialog, :jquery_link_to_remote_dialog
      
      #
      # @author ericsk
      # @since 0.2
      def jquery_link_to_remote_box(name, options = {}, box = {}, html = {})
        unless box[:id] and box[:id].length > 0
          box[:id] = "my_box#{@@box_seq}"
          @@box_seq = @@box_seq + 1
        end
        
        j = javascript_tag("$(document).keydown(function(event){if (event.keyCode == 27) {$(document).uiRemoveBox();}});" +
          "$(window).scroll(function(event){$(document).uiAdjustBox();});");
        
        options[:update] = box[:id]
        # add overlay
        j.concat(content_tag("a", name, html.merge({
          :href => html[:href] || "#",
          :onclick => "$(document).uiAddBox('#{box[:id]}'); #{jq_remote_func(options)}; return false;"})))
      end
      alias_method :jq_link_to_remote_box, :jquery_link_to_remote_box
      
    end
  end
end
